package ru.dc.gui.swing;

import ru.dc.gui.UserStoreEvent;
import ru.dc.gui.UserStoreListener;
import ru.dc.gui.UsersStore;
import ru.dc.object.UserInfo;

import javax.swing.table.AbstractTableModel;
import java.util.Collection;
import java.util.List;

/**
 * <pre>
 * User: Penkov Vladimir
 * Date: 02.11.2010
 * Time: 10:33:08
 * </pre>
 */
public class UsersModel extends AbstractTableModel {

    private String[] columnNames = {"Имя", "Размер"};
    private UsersStore users = new UsersStore();
    private UsersModel.UsersStoreToTableModelEventsTranslator usersStoreListener;

    public UsersModel() {
        usersStoreListener = new UsersStoreToTableModelEventsTranslator();
        users.addEventListener(usersStoreListener);
    }

    public int getRowCount() {
        return users.getSize();
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case 0:
                return String.class;
            case 1:
                return Long.class;
        }
        return super.getColumnClass(columnIndex);
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return users.getUser(rowIndex).getNick();
            case 1:
                return users.getUser(rowIndex).getSharesize();
        }
        return super.getColumnClass(columnIndex);
    }

    public void addUser(UserInfo nick) {
        users.addUser(nick);
    }

    public void addUsers(Collection<UserInfo> users) {
        this.users.addUsers(users);
    }

    public void removeUser(UserInfo userInfo) {
        users.removeUser(userInfo);
    }

    public void removeUser(String nick) {
        users.removeUser(nick);
    }

    public void clear() {
        users.clear();
    }

    public List<UserInfo> getUsers() {
        return users.getUsers();
    }

    private class UsersStoreToTableModelEventsTranslator implements UserStoreListener {

        public void onEvent(UserStoreEvent event) {
            switch (event.getType()) {
                case UserStoreEvent.USER_ADDED:
                    fireTableRowsInserted(event.getIndex(), event.getIndex());
                    break;
                case UserStoreEvent.USER_REMOVED:
                    if (event.getIndex()>=0) {
                        fireTableRowsDeleted(event.getIndex(), event.getIndex());
                    }
                    else {
                        fireTableDataChanged();
                    }
                    break;
                case UserStoreEvent.USER_UPDATED:
                    fireTableRowsUpdated(event.getIndex(), event.getIndex());
                    break;
            }
        }
    }
}
